from datetime import datetime, timedelta
import json
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings
from application.http.models.code.Code import Code


router = APIRouter(prefix='/brand/theme', tags=['Brand'])
module_name = '品牌商模块 - v3模板'


@router.get('', response_model=schemas.BaseApiListOut)
async def get_templates(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    # brand_id: Optional[int] = None,
    code: Optional[str] = None,
    template_type: Optional[int] = 0,
    code_type: Optional[int | str] = None,
    channel: Optional[int] = None,
    push_status: Optional[int | str] = None,
    version: Optional[int | str] = 3,
    keyword: Optional[str] = None,
):
    """
        品牌商 v3模板列表
    """

    objs = CodeModel.TenantTemplate.with_('brand')

    # if brand_id:
    #     objs = objs.where('brand_id', brand_id)
    if code:
        objs = objs.where('code', code)

    if template_type >= 0:
        objs = objs.where('template_type', template_type)
    if code_type:
        objs = objs.where('code_type', code_type)
    if channel:
        objs = objs.where('channel', channel)

    if push_status:
        objs = objs.where('push_status', push_status)
    if version:
        objs = objs.where('version', version)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'title', 'like', f'%{keyword}%'
            ).or_where(
                'theme_code', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('', response_model=schemas.BaseApiOut)
async def add_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: dict = Body(...),
):
    """
        添加模板
    """

    # 生成 theme_code
    theme_code = ''.join(Helper.random_str(length=10, ctype=5))
    while CodeModel.TenantTemplate.where('theme_code', theme_code).first():
        theme_code = ''.join(Helper.random_str(length=10, ctype=5))

    # 品牌商信息
    brand = None
    if post.get('brand_id'):
        brand = OemModel.Company.where('brand_id', post.get('brand_id')).first()

    try:
        obj = CodeModel.TenantTemplate.create(
            theme_code=theme_code,
            code=brand.code if brand else None,
            title=post['title'],
            channel=post['channel'],
            code_type=post['code_type'],
            is_default=post['is_default'],
            remarks=post['remarks'],
            template_type=post['template_type'],
            version=post['version'],
            thumb=post['thumb'],
            theme_content=json.dumps(post['theme_content']),
        )

        obj = obj.fresh()

        if int(post['template_type']) == 0 and int(post['is_default']) == 1:
            # 判断是否有其它域名 清空其它域名的默认主域名设置
            CodeModel.TenantTemplate.where('id', '!=', obj.id).where(
                'template_type', 0
            ).where(
                'code_type', post['code_type']
            ).where(
                'channel', post['channel']
            ).update({
                'is_default': 0
            })
        if int(post['template_type']) > 0 and int(post['is_default']) == 1:
            # 判断商户是不是需要重置默认模板
            CodeModel.TenantTemplate.where('id', '!=', obj.id).where(
                'template_type', '>', 0
            ).where(
                'code', obj.code
            ).where(
                'code_type', post['code_type']
            ).where(
                'channel', post['channel']
            ).update({
                'is_default': 0
            })

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.post('/push/{id}', response_model=schemas.BaseApiOut)
async def push_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    """
        推送模板
    """

    obj = CodeModel.TenantTemplate.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        # 平台推送状态 0未推送(默认) 1已推送 2无需要推送
        obj.push_status = 1
        obj.save()

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.post('/default/{id}', response_model=schemas.BaseApiOut)
async def default_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    """
        设置默认模板
    """

    obj = CodeModel.TenantTemplate.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        # 判断是否有其它同类型 清空其它的默认主域名设置
        # 码类型 针对码类型 1 刮刮码 2 防伪码
        # 渠道 1 H5 2 PC 3 微信小程序
        update_obj = CodeModel.TenantTemplate.where(
            'code_type', obj.code_type
        ).where(
            'channel', obj.channel,
        )
        # 是否非系统平台
        if obj.code is not None:
            update_obj = update_obj.where('code', obj.code)

        update_obj.update({
            'is_default': 0
        })

        # 设置自身为默认模板
        obj.is_default = 1
        obj.save()

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.post('/copy/{id}', response_model=schemas.BaseApiOut)
async def copy_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
    post: dict = Body(),
):
    """
        复制模板
    """

    obj = CodeModel.TenantTemplate.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    company = OemModel.Company.where('code', post['code']).first()
    if company is None:
        return schemas.BaseApiOut(code=1, message='商户不存在')

    # 生成 theme_code
    theme_code = ''.join(Helper.random_str(length=10, ctype=5))
    while CodeModel.TenantTemplate.where('theme_code', theme_code).first():
        theme_code = ''.join(Helper.random_str(length=10, ctype=5))

    try:
        c_obj = CodeModel.TenantTemplate.create(
            theme_code=theme_code,
            template_type=1,  # 模板类型 0 系统模板(默认) 1 商户模板 2 定制模板
            code=post['code'],
            is_default=post['is_default'],
            title=obj.title,
            code_type=obj.code_type,
            channel=obj.channel,
            remarks=obj.remarks,
            version=obj.version,
            thumb=obj.thumb,
            push_status=obj.push_status,
            theme_content=json.dumps(obj.theme_content),
            user_id=current_user.id,
        )

        if int(post.get('is_default')) == 1:
            # 判断是否有其它同类型 清空其它的默认主域名设置
            # 码类型 针对码类型 1 刮刮码 2 防伪码
            # 渠道 1 H5 2 PC 3 微信小程序
            CodeModel.TenantTemplate.where(
                'id', '!=', c_obj.fresh().id
            ).where(
                'code', post['code']
            ).where(
                'code_type', obj.code_type
            ).where(
                'channel', obj.channel,
            ).update({
                'is_default': 0
            })

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.put('/{id}', response_model=schemas.BaseApiOut)
async def edit_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
    post: dict = Body(),
):
    """
        编辑模板
    """

    obj = CodeModel.TenantTemplate.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    try:
        # 更新
        obj.title = post['title']
        obj.is_default = post['is_default']
        obj.version = post['version']
        obj.channel = post['channel']
        obj.code_type = post['code_type']
        obj.remarks = post['remarks']
        obj.template_type = post['template_type']
        obj.thumb = post['thumb']
        obj.theme_content = post['theme_content']
        obj.save()

        if post['template_type'] == 0 and post['is_default'] == 1:
            # 判断是否有其它域名 清空其它域名的默认主域名设置
            CodeModel.TenantTemplate.where('id', '!=', obj.id).where(
                'template_type', 0
            ).where(
                'code_type', post['code_type']
            ).where(
                'channel', post['channel']
            ).update({
                'is_default': 0
            })
        if post['template_type'] > 0 and post['is_default'] == 1:
            # 判断商户是不是需要重置默认模板
            CodeModel.TenantTemplate.where('id', '!=', obj.id).where(
                'template_type', '>', 0
            ).where(
                'code', obj.code
            ).where(
                'code_type', post['code_type']
            ).where(
                'channel', post['channel']
            ).update({
                'is_default': 0
            })

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')


@router.delete('/{id}', response_model=schemas.BaseApiOut)
async def delete_template(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    """
        删除模板
    """

    obj = CodeModel.TenantTemplate.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此信息不存在')

    # 是否已经推送 或 是否已经默认
    if obj.is_default == 1 or (obj.push_status is not None and obj.push_status > 0):
        return schemas.BaseApiOut(code=1, message='默认和已推送模板不能删除')

    try:
        obj.delete()

        return {'message': '操作成功'}
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')
